package com.xs.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

// 登录拦截器
public class LoginInterceptor implements HandlerInterceptor {

    // 设置白名单
    private Set<String> whiteUrls = new HashSet<>();

    public LoginInterceptor() {
        // 自定义放行路径
        whiteUrls.add("/login");
        whiteUrls.add("/adminLogin.html");
        // 。。。。。
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截器preHandel");

        // 获取当前正在访问的路径
        String requestURL = request.getRequestURL().toString();// http://localhost:8080/index.html
        String requestURI = request.getRequestURI();// index.html

        System.out.println("requestURL：" + requestURL);
        System.out.println("requestURI：" + requestURI);

        // 遍历白名单
        for (String url : whiteUrls) {
            // 判断
            if (requestURL.endsWith(url)) {
            return true;
            }
        }

        // 如若已有登录，将放行
        HttpSession session = request.getSession(false);
        // 判断 登录状态是否存在
        if (session != null) {
            // 判断
            if (session.getAttribute("admin") != null) {
                return true;
            }
        }

        // 未登录去登录页面
        // 请求.获取请求调度程序
//        request.getRequestDispatcher("adminLogin.html").forward(request,response);
        response.sendRedirect("adminLogin.html");
        return false;
    }
}
